package com.ranshiyan.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageInfo;
import com.ranshiyan.entity.Applicant;
import com.ranshiyan.entity.Job;
import com.ranshiyan.entity.Score;
import com.ranshiyan.service.JobService;

@Controller
public class JobController {

	@Autowired
	JobService jobService;
	
	//flag查询条件 0:全部内部  1:90分以上   2:80分以上   3:研究生以上
	@RequestMapping("list")
	public String list(HttpServletRequest request,@RequestParam(defaultValue="0") int flag,
			@RequestParam(defaultValue="1") int page) {
		PageInfo<Applicant> pageApplicant = jobService.list(page,flag);
		request.setAttribute("pageApplicant", pageApplicant);
		
		return "list";
	}
	
	//跳转到添加应聘者的页面
	@RequestMapping("toAdd")
	public String addApplicant(HttpServletRequest request) {
		return "add";
	}
	
	//接收应聘者的数据保存到数据库
	@RequestMapping("add")
	public String addApplicant(HttpServletRequest request,
			@ModelAttribute("applicant") @Valid Applicant applicant,BindingResult result) {
		
		if((applicant.getEdu()==1 || applicant.getEdu()==2) 
				&& ( applicant.getDegree()!=1) ) {
			result.rejectValue("degree", "degree", "学历为专科或本科的时候，学位只能是学士");
		}
		if(applicant.getEdu()==3) {
			if( !(applicant.getDegree()==2||applicant.getDegree()==2)) {
				// 通过  不合法
				result.rejectValue("degree", "degree", "学历研究生时候，学位只能是硕士或博士");
			}
		}
		if(result.hasErrors()) {
			return "add";
		}
		jobService.add(applicant);
		//调用添加到数据库的业务
		return "redirect:list";
	}
	
	//跳转到添加成绩的页面,需要应聘者的id
	@RequestMapping("toAddScore")
	public String addScore(HttpServletRequest request,int aid) {
		
		//获取求职者的信息
		Applicant applicant = jobService.getApplicant(aid);
		//获取所有的工作下拉框显示
		List<Job> jobs = jobService.listJobs();
		request.setAttribute("applicant", applicant);
		request.setAttribute("jobs", jobs);
		return "addScore";
	}
	
	//添加成绩
	@RequestMapping("addScore")
	public String addScore(HttpServletRequest request,
			@ModelAttribute("score") @Valid Score score,BindingResult result) {
		if(result.hasErrors()) {
			return "addScore";
		}
		jobService.addScore(score);
		return "redirect:list";
	}
}
